<template>
    <div class="login-bg">
        <div class="login-card">
            <h2>租户注册</h2>
            <el-form :model="form" :rules="rules" ref="formRef" class="login-form" @keyup.enter="submitRegister"
                label-width="100px" label-position="left">
                <el-form-item label="企业名称" prop="tenantName">
                    <el-input v-model="form.tenantName" placeholder="请输入企业名称" />
                </el-form-item>
                <el-form-item label="租户图标" prop="tenantIcon">
                    <el-upload class="avatar-uploader" action="" :show-file-list="false" :before-upload="beforeUpload"
                        :on-change="handleIconChange" :auto-upload="false">
                        <img v-if="form.tenantIconPreview" :src="form.tenantIconPreview" class="avatar"
                            @click="previewIcon" />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <div v-if="form.tenantIconPreview" class="icon-actions">
                        <el-button icon="el-icon-zoom-in" size="mini" @click="previewIcon">预览&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button>
                        <el-button icon="el-icon-delete" size="mini" @click="addDeleteIcon">删除&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button>
                    </div>
                    <div style="font-size: 12px; color: #999; margin-left: 10px; margin-top: 4px;">支持上传 jpg/png/jpeg 图片，大小不超过5MB</div>
                </el-form-item>
                <el-form-item label="联系人" prop="contactPerson">
                    <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
                </el-form-item>
                <el-form-item label="联系电话" prop="contactPhone">
                    <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="管理员账号" prop="adminName">
                    <el-input v-model="form.adminName" placeholder="请输入管理员账号" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                    <el-row :gutter="8" style="width: 100%">
                        <el-col :span="14">
                            <el-input v-model="form.code" placeholder="请输入验证码" maxlength="5" />
                        </el-col>
                        <el-col :span="10">
                            <img :src="captchaImg" @click="getCaptcha"
                                style="height: 36px; cursor: pointer; border-radius: 4px; border: 1px solid #eee;"
                                :title="'点击刷新验证码'" />
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" style="width: 100%;" :loading="loading"
                        @click="submitRegister">注册</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="text" style="width: 100%;" @click="goLogin">已有账号？去登录</el-button>
                </el-form-item>
            </el-form>
            <el-dialog v-model="iconPreviewVisible" width="300px" title="图标预览">
                <img :src="form.tenantIconPreview" style="width: 100%;" />
            </el-dialog>
            <el-dialog title="注册结果" v-model="resultDialogVisible" width="350px" show-close>
                <span>{{ resultMessage }}</span>
                <template #footer>
                    <el-button type="primary" @click="resultDialogVisible = false">关闭</el-button>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import TenantService from '../services/TenantService';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

const router = useRouter();
const form = reactive({
    tenantName: '',
    tenantIcon: '',
    tenantIconFile: null,
    tenantIconPreview: '',
    contactPerson: '',
    contactPhone: '',
    adminName: '',
        password: '',
    code: '',
    remark: ''
});

const rules = {
    tenantName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
    contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
    contactPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    adminName: [{ required: true, message: '请输入管理员账号', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
};
const formRef = ref();
const loading = ref(false);
const captchaImg = ref('');
const resultDialogVisible = ref(false);
const resultMessage = ref('');
const iconPreviewVisible = ref(false);



function goLogin() {
    router.push('/login');
}

async function getCaptcha() {
    try {
        const res = await TenantService.getCaptcha();
        if (res.code === 200 && res.data) {
            captchaImg.value = res.data.img;
            form.uuid = res.data.uuid;
        }
    } catch (e) {
        captchaImg.value = '';
    }
}

onMounted(() => {
    getCaptcha();
});

function showResult(msg) {
    resultMessage.value = msg;
    resultDialogVisible.value = true;
}

function submitRegister() {
    formRef.value.validate(async (valid) => {
        if (!valid) return;
        loading.value = true;
        try {
            const tenant = {
                tenantName: form.tenantName,
                tenantIcon: form.tenantIcon,
                contactPerson: form.contactPerson,
                contactPhone: form.contactPhone,
                adminName: form.adminName,
                password: form.password,
                code: form.code,
                uuid: form.uuid
            }
            const res = await TenantService.register(form.tenantIconFile, tenant);
            console.log("sdgfsd",res);
            if (res.code === 200) {
                showResult('注册成功！请返回登录页面登录。');
            } else {
                showResult(res.msg || '注册失败');
                getCaptcha();
            }
        } catch (e) {
            showResult('注册失败');
            getCaptcha();
        } finally {
            loading.value = false;
        }
    });
}

function beforeUpload(file) {
    const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isImage) {
        showError('仅支持 jpg/png/jpeg 格式图片');
        return false;
    }
    if (!isLt5M) {
        showError('图片大小不能超过5MB');
        return false;
    }
    return true;
}


function handleIconChange(file) {
    // 只做本地预览，不上传
    if(form.tenantId){
        deleteIconFlag.value = 1;
    }

    if (!beforeUpload(file.raw)) return;
    form.tenantIconFile = file.raw;

    const reader = new FileReader();
    reader.onload = e => {
        form.tenantIconPreview = e.target.result;
    };
    reader.readAsDataURL(file.raw);

}

function previewIcon() {
    iconPreviewVisible.value = true;
}

function addDeleteIcon() {
    form.tenantIcon = '';
    form.tenantIconFile = null;
    form.tenantIconPreview = '';
    deleteIconFlag.value = 1;
}


</script>

<style scoped>
.login-bg {
    width: 100vw;
    height: 100vh;
    background: url('/src/assets/background.png') center center/cover no-repeat;
    display: flex;
    align-items: center;
    justify-content: center;
}

.login-card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 8px;
    box-shadow: 0 4px 24px rgba(0, 0, 0, 0.15);
    padding: 36px 32px 24px 32px;
    min-width: 700px;
    min-height: 320px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.login-card h2 {
    margin-bottom: 24px;
    font-weight: bold;
    color: #333;
    letter-spacing: 2px;
}

.login-form {
    width: 100%;
}

.el-form-item__label {
    justify-content: flex-start !important;
    text-align: left !important;
}


.tenant-actions {
    margin-bottom: 10px;
    margin-left: 10px;
}

.avatar-uploader {
    display: inline-block;
    width: 80px;
    height: 80px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
    margin-right: 10px;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
}

.avatar {
    width: 80px;
    height: 80px;
    display: block;
    border-radius: 6px;
}

.icon-actions {
    margin-top: 8px;
}
</style>